package com.ljx.itbbs.server.article.event.handler;

import com.ljx.itbbs.server.article.domain.enums.CollectEnum;
import com.ljx.itbbs.server.article.domain.enums.LikeEnum;
import com.ljx.itbbs.server.article.event.CollectEvent;
import com.ljx.itbbs.server.article.event.LikeEvent;
import com.ljx.itbbs.server.article.service.ArticleService;
import com.ljx.itbbs.server.article.service.CollectRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-03-27  19:54
 */
@Component
public class CollectEventHandler {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CollectRecordService collectRecordService;

    /**
     * 增加浏览量
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = CollectEvent.class, fallbackExecution = true)
    public void increaseCollectNum(CollectEvent event) {
        if (event.getType().equals(CollectEnum.ARTICLE.getType())){
            articleService.increaseCollectNum(event.getObjId());
        }
    }

    /**
     * 保存记录
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = CollectEvent.class, fallbackExecution = true)
    public void saveCollectRecord(CollectEvent event) {
        collectRecordService.saveCollectRecord(event.getObjKey(), event.getUserId(), event.getType());
    }

}
